import datetime
import re

from exts import db
from models import Article, Category
from utils import validate_url

def add_article(user_id, username, title, content, cover_img, state, category_id):
    article = Article.query.filter_by(title=title).first()
    category = Category.query.filter_by(category_id=category_id)

    if not category:
        raise Exception("文章分类不正确")

    if article:
        raise Exception("文章已存在")

    if not re.findall(r".{1,10}", title):
        raise Exception("文章标题不合法，长度应在1-10之间")

    if not validate_url(cover_img):
        raise Exception("文章封面图url不合法")

    if state not in ['已发布', '草稿']:
        raise Exception("状态只能为已发布或草稿")

    article = Article(category_id=category_id,
                      title=title,
                      content=content,
                      cover_img=cover_img,
                      state=state,
                      create_user_id=user_id,
                      create_user_name=username,
                      create_time=datetime.datetime.now(),
                      update_time=datetime.datetime.now())

    db.session.add(article)

    try:
        db.session.commit()
        return True
    except Exception as ex:
        raise ex


def get_article(category_id, title, state, create_user_name,page,size):
    sql = Article.query

    if title:
        sql = sql.filter(Article.title.like(f'%{title}%'))
    if category_id:
        sql = sql.filter_by(category_id=category_id)
    if state:
        sql = sql.filter_by(state=state)
    if create_user_name:
        sql = sql.filter_by(create_user_name=create_user_name)

    pagination = sql.paginate(page=page,per_page=size)
    article_list = pagination.items
    total = pagination.total

    article_list = [article.to_dict() for article in article_list]
    return article_list

def delete_article(article_id):
    article = Article.query.filter_by(article_id=article_id).first()

    if not article:
        raise Exception("文章不存在")

    db.session.delete(article)
    try:
        db.session.commit()
        return True
    except Exception as ex:
        raise ex

def update_article(article_id,title,content,cover_img,state,category_id):
    article = Article.query.filter_by(article_id=article_id).first()
    if not article:
        raise Exception("文章不存在")

    if title:
        if not re.findall(r".{1,10}", title):
            raise Exception("文章标题不合法，长度应在1-10之间")
        article.title = title

    if cover_img:
        if not validate_url(cover_img):
            raise Exception("文章封面图url不合法")
        article.cover_img = cover_img

    if state:
        if state not in ['已发布', '草稿']:
            raise Exception("状态只能为已发布或草稿")
        article.state = state

    if category_id:
        category = Category.query.filter_by(category_id=category_id)
        if not category:
            raise Exception("文章分类不正确")
        article.category_id = category_id

    if content:
        article.content = content

    article.update_time = datetime.datetime.now()
    try:
        db.session.commit()
        return True
    except Exception as ex:
        raise ex
